<template>
	<view class="contener">
		<view :class="['sub_title',{'active':distance && distance<=checkInDistance}]">
			<view class="ico-box">
				<image style="width: 30px; height: 30px;margin-bottom: 10rpx;"
					:src="distance && distance<=checkInDistance?'/static/gridManagement/activeClockIn.png':'/static/gridManagement/unActiveClockIn.png'">
				</image>
				<u-icon name="checkmark-circle-fill" :color="distance && distance<=checkInDistance?'#7EAD17':'#a7a0a0'"
					label-color="#fff"></u-icon>
			</view>

			<view style="display: flex;" :style="{color:distance && distance<=checkInDistance?'#7EAD17':'#a7a0a0'}">
				<text style="margin-right: 8rpx;">
					您{{distance && distance<=checkInDistance?"已":"不"}}在签到范围内
				</text>
				<!-- <u-icon name="info-circle" v-if="!distance || distance>checkInDistance"
					:color="distance && distance<=checkInDistance?'#FFC300':'#a7a0a0'" size="20"
					:closeOnClickOverlay="true" @click="showHelp"></u-icon> -->
			</view>
		</view>
		<view class="clock_in" @click="checkIn">
			<text>{{checkInId==null || checkInId=='null'?'签入':'签出'}}</text>
			<text>{{curentTime}}</text>
		</view>
		<view style="display: flex;justify-content: center;margin-top: 30rpx;" @click="refresh">
			<uni-icons type="refresh" size="25"></uni-icons>
			<text style="margin-left: 5rpx;">刷新</text>
		</view>


		<u--text type="info" text="查看帮助" align="center" prefixIcon="question-circle"
			v-if="!distance || distance>checkInDistance" @click="showHelp"
			style="position: fixed;bottom: 60rpx;    left: 50%;transform: translateX(-50%);"></u--text>


		<u-modal :show="show" :title="title" :content='getHelpContent' @confirm="closeHelp"></u-modal>
	</view>
</template>

<script>
	import {
		securityJsCode,
		key
	} from '@/config/env.js'
	let timer = null;
	import moment from 'moment'
	import AMapLoader from "@amap/amap-jsapi-loader";
	import {
		calculateDistance
	} from '@/common/api/map.js'

	import {
		findCurentDayDataByCid,
		add
	} from '@/common/api/JzzxCheckIn.js'
	export default {
		props: ['cid', 'checkInId', 'longitude', 'latitude', 'address', 'cname', 'system'],
		data() {
			return {
				curentTime: '', //当前时间
				curentLongitude: null,
				curentLatitude: null,
				distance: null,
				show: false,
				title: '查看帮助',

				checkInDistance: 300 //多少米内可以进行打卡
			}
		},
		computed: {
			getHelpContent: function() {

				if (this.distance != null) {
					var distanceStr = "";
					if (this.distance < 1000) {
						return `${this.checkInDistance}米内，才能进行打卡；您目前距离目的地${this.distance}m。`
					} else {

						return `${this.checkInDistance}米内，才能进行打卡；您目前距离目的地${(this.distance/1000).toFixed(1)}km。`
					}
				} else {
					return `检查是否网络不好或手机是否开启定位功能，目前无法获取定位信息！`
				}

			}
		},
		mounted() {

			this.onSetTimeout()

			//获取当前位置是否在范围内
			this.getCurrentLatLon()
		},
		beforeUnmount() {

			this.clearTimer();
		},
		methods: {
			onSetTimeout() {
				if (!timer) {
					timer = setInterval(() => {
						this.curentTime = moment().format('HH:mm:ss');
					}, 1000);
				} else {
					clearInterval(timer);
					timer = setInterval(() => {
						this.curentTime = moment().format('HH:mm:ss');
					}, 1000);
				}

			},
			clearTimer() {
				// clearTime
				if (timer) {
					clearInterval(timer);
					timer = null;
				}
			},
			//刷新位置
			refresh() {
				this.getCurrentLatLon()
			},
			closeHelp() {
				this.show = false
			},
			showHelp() {

				this.show = true
			},

			checkIn() { //签到
				const env = process.env.NODE_ENV;
				debugger
				if (env == 'development') {
					this.saveCheckInData()
					return;
				}


				if (!this.distance) {
					uni.showToast({
						title: '请刷新重试！',
						icon: 'none',
						duration: 2000
					});
				} else if (this.distance && this.distance >= this.checkInDistance) { //不在范围内
					uni.showToast({
						title: '不在范围内！',
						icon: 'none',
						duration: 2000
					});
				} else {
					if (this.checkInId == null || this.checkInId == 'null') {
						this.saveCheckInData()

					} else {
						uni.showModal({
							title: '提示',
							content: '请记得要填写拜访记录哦？',
							success: (res) => {
								if (res.confirm) {
									this.saveCheckInData()
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}

				}
			},
			//保存签到数据
			saveCheckInData() {

				var form = {
					id: this.checkInId,
					customerId: this.cid,
					longitude: this.curentLongitude,
					latitude: this.curentLatitude,
					address: this.address,
					customerName: this.cname,
					system: this.system
				}
				add(form).then((
					data
				) => {
					console.log(data)
					if (data.code == 200) {
						uni.showToast({
							title: '打卡成功',
							duration: 2000
						});
						this.$emit('update:checkInId', data.data);
						// this.$parent.changeCheckInId(data.data)
						// this.checkInId = data.data
					}
				})
			},
			getCurrentLatLon() {
				uni.showLoading({
					title: '请稍等...'
				});
				// alert("初始化地图")
				//alert(curentLongitude.value, curentLatitude.value)
				window._AMapSecurityConfig = {
					securityJsCode: securityJsCode,
				};
				// alert("1")
				console.log("1..............")
				AMapLoader.load({
						key: key, // 申请好的Web端开发者Key，首次调用 load 时必填
						version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
						plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
					})
					.then((AMap) => {
						// alert("2")
						console.log("2..............")
						AMap.plugin('AMap.Geolocation', () => {
							var geolocation = new AMap.Geolocation({
								enableHighAccuracy: true, //是否使用高精度定位，默认:true
								timeout: 10000, //超过10秒后停止定位，默认：5s
								position: 'RB', //定位按钮的停靠位置
								offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
								zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点

							});


							// this.map.addControl(geolocation);
							geolocation.getCurrentPosition((status, result) => {
								// alert("3")
								console.log("3..............")
								if (status == 'complete') {
									// alert("获取成功")
									// alert("4")
									console.log("4..............")
									var startLonLat = JSON.parse(JSON.stringify(result.position))
									this.curentLongitude = startLonLat[0]
									this.curentLatitude = startLonLat[1]

									// alert(JSON.stringify(result.position))
									// alert(this.curentLongitude + "....." + this.curentLatitude)
									// alert("当前位置" + this.curentLongitude + "....." + this
									// 	.curentLatitude)

									// alert("客户位置" + this.longitude + "....." + this
									// 	.latitude)

									calculateDistance({
										startLng: this.curentLongitude,
										startLat: this.curentLatitude,
										endLng: this.longitude,
										endLat: this.latitude,
										flg: '1'
									}).then(({
										data
									}) => {
										this.distance = data

										uni.hideLoading();
										// alert(JSON.stringify(data))
									}).catch((error) => {
										alert(JSON.stringify(error))
										console.error("失败：" + error); // 如果状态是 rejected，执行这里
										uni.hideLoading();
									})

								} else {
									// alert("5")
									console.log("5..............")


									uni.hideLoading();
								}
							});
						});

					})
					.catch((e) => {
						// alert("3")
						alert(e);
					});
			}
		}
	}
</script>

<style scoped lang="scss">
	page {
		height: 100%;
	}

	.contener {
		display: flex;
		flex-direction: column;
		// justify-content: center;
		align-items: center;
		height: 100%;
		padding-top: 200rpx;
	}

	.sub_title {
		margin-bottom: 80rpx;

		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
		color: #a7a0a0;


		.active {
			color: #7EAD17;
		}

		.ico-box {
			position: relative;

			::v-deep .u-icon {

				position: absolute;
				right: -16rpx;
				bottom: 12rpx;


			}
		}
	}

	.clock_in {
		width: 240rpx;
		height: 240rpx;
		border: 20rpx solid #FFC300;
		border-radius: 240rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
</style>